import store from '@/store'
import { checkBeforeInsert } from '@/utils/helpers'

/* eslint-disable no-undef */
tinymce.PluginManager.add('kityformula', function (editor) {
  var baseURL = tinymce.baseURL + '/tinymce/plugins/kityformula/index.html'
  // 复制来自于 src\plugins\image\plugin.js
  var isNullable = function (a) {
    return a === null || a === undefined
  }
  var isNonNullable = function (a) {
    return !isNullable(a)
  }
  var getSelectedImage = function (editor) {
    var imgElm = editor.selection.getNode()
    var figureElm = editor.dom.getParent(imgElm, 'figure.image')
    if (figureElm) {
      return editor.dom.select('img', figureElm)[0]
    }
    if (imgElm && (imgElm.nodeName !== 'IMG' || isPlaceholderImage(imgElm))) {
      return null
    }
    return imgElm
  }
  var getSelectedFormula = function (elm) {
    return elm ? editor.dom.getParent(elm, 'div[data-type="formula"]') :  null
  }

  editor.on('dblclick', function () {
    var sel = editor.selection.getContent()
    // eslint-disable-next-line no-useless-escape
    var path = /\<img(.*?)src="[A-Za-z0-9\-\:\/\.]*"(.*?)data-img-latex="(.+?)" \/>/g
    var path1 = /\<img(.*?)src="data:image\/png;base64,[A-Za-z0-9+/=]+"(.*?)data-img-latex="(.+?)" \/>/g
    var path2 = /data-img-latex="(.+?)"/g
    var path3 = /\<img(.*?)src="[A-Za-z0-9\-\:\/\.]*"(.*?)data-latex="(.+?)" \/>/g
    var path4 = /data-latex="(.+?)"/g

    if (sel.search(path3) == 0) {
      var node = editor.selection.getNode()
      store.commit('xmleditor/SET_EDITING_FORMULA', { id: node.dataset.id, type: 'inline_formula_type' })

      sel.replace(path4, function ($0, $1) {
        var param = encodeURIComponent($1)
        openDialog(param)
        return $0
      })
      return
    }

    if (sel.search(path) == 0 || sel.search(path1) == 0) {
      var node = tinymce.activeEditor.dom.getParent(editor.selection.getNode(), '[data-type="formula"]')
      store.commit('xmleditor/SET_EDITING_FORMULA', { id: node.dataset.id, type: 'formula_type' })

      sel.replace(path2, function ($0, $1) {
        var param = encodeURIComponent($1)
        openDialog(param)
        return $0
      })
    }
  })

  var openDialog = function (param, type) {
    const editingFormulaType = store.state.xmleditor.editingFormulaType
    const buttons = [{ type: 'cancel', text: 'Close' }]
    const saveBtn = { type: 'custom', text: '保存', name: 'save', primary: true }
    let title = '插入公式'
    if (editingFormulaType=== 'inline_formula_type' || type === 'inline_formula_type') {
      saveBtn.name = 'inline_formula'
      title = '插入行内公式'
    }
    buttons.push(saveBtn)


    return editor.windowManager.openUrl({
      title,
      size: 'large',
      width: 850,
      height: 500,
      url: param ? baseURL + '?c=' + param : baseURL,
      buttons,
      onAction: function (api, details) {
        switch (details.name) {
          case 'inline_formula':
            if (!checkBeforeInsert('inline_formula')) return
            api.sendMessage('save_inline_formula')
            break
          case 'save':
            if (!checkBeforeInsert('formula')) return
            api.sendMessage('save')
            break
          default:
            break
        }
      }
    })
  }

  // 增加公式编辑器图标
  editor.ui.registry.addIcon('kityformula-icon', '<svg width="24" height="25" viewBox="0 0 24 25" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g transform="translate(-1008.000000, -161.000000)" fill="#000000" fill-rule="nonzero"> <g transform="translate(16.000000, 149.500000)"> <g transform="translate(190.000000, 8.000000)"> <g transform="translate(802.000000, 3.500000)"> <rect opacity="0" x="0" y="0.5" width="24" height="24"></rect> <g transform="translate(0.500000, 5.485672)"> <path d="M8.77167795,7.46255573 L3.61145412,1.19704158 L8.84543174,1.19704158 C8.84543174,1.19704158 10.687662,1.05602147 11.3511471,1.9713517 C12.0147219,2.88671181 12.2357142,4.29467069 12.2357142,4.29467069 L12.8992591,4.29467069 L12.6046326,0 L0,0 L0,0.633588967 L6.48626727,8.23683595 L0,15.4882053 L0,16.1922894 L12.8992292,16.1922894 L13.7102817,11.404721 L13.0468265,11.2640297 C13.0468265,11.2640297 12.8257445,12.3200811 11.9410877,13.3055776 C11.0565206,14.2913431 7.59197614,14.1503828 7.59197614,14.1503828 L2.94829787,14.1503828 L8.77170785,7.46258563 L8.77167795,7.46255573 Z M15.0911247,12.9397385 L14.5661485,12.5700727 L20.5074987,3.35942963 L21.0317874,3.72873669 L15.0911247,12.9397385 M15.3740618,7.38464638 C15.1842213,7.38464638 15.0577009,7.25247553 15.0577009,7.05396514 L15.0577009,3.58317237 C15.0577009,3.38481146 15.1842213,3.25255092 15.3740618,3.25255092 C15.5638426,3.25255092 15.6904228,3.38481146 15.6904228,3.58317237 L15.6904228,7.08703027 C15.6904228,7.25250543 15.5322423,7.38464638 15.3740618,7.38464638 L15.3740618,7.38464638 Z" id="形状"></path> <path d="M13.5386778,4.97157917 L17.1776364,4.97157917 C17.3675965,4.97157917 17.4940871,5.10372012 17.4940871,5.30205114 C17.4940871,5.50038215 17.3675965,5.63270248 17.1776364,5.63270248 L13.5386778,5.63270248 M22.6834895,10.8224338 L19.0445907,10.8224338 C18.8545709,10.8224338 18.7282298,10.6903526 18.7282298,10.4918721 C18.7282298,10.2933618 18.8547203,10.1612806 19.0445907,10.1612806 L22.6834596,10.1612806 C22.8734197,10.1612806 23,10.2936009 23,10.4918721 C22.9998505,10.6903825 22.8734197,10.8224338 22.6834895,10.8224338 Z M22.6518594,9.07046001 L19.0129307,9.07046001 C18.8229407,9.07046001 18.6964502,8.93819947 18.6964502,8.73983856 C18.6964502,8.54168692 18.8229407,8.40936659 19.0129307,8.40936659 L22.6518594,8.40936659 C22.8418793,8.40936659 22.9682802,8.54168692 22.9682802,8.73983856 C22.9682802,8.93822937 22.8418793,9.07046001 22.6518893,9.07046001 L22.6518594,9.07046001 Z" id="形状"></path> </g> </g> </g> </g> </g> </g> </svg>' );
  editor.ui.registry.addMenuButton('kityformula', {
    icon: 'kityformula-icon',
    tooltip: '公式',
    onSetup: function (buttonApi) {
      buttonApi.setActive(isNonNullable(getSelectedFormula(getSelectedImage(editor))))
      return editor.selection.selectorChangedWithUnbind(
        'div[data-type="formula"],img[data-type$="formula"]',
        buttonApi.setActive
      ).unbind
    },
    fetch: function (callback) {
      callback([
        {
          type: 'menuitem',
          text: '公式',
          onAction: function() {
            if (!checkBeforeInsert('formula')) return
            store.commit('xmleditor/SET_EDITING_FORMULA', { id: null, type: null })
            openDialog(null, 'formula_type')
          }
        },
        {
          type: 'menuitem',
          text: '行内公式',
          onAction: function() {
            if (!checkBeforeInsert('inline_formula')) return
            store.commit('xmleditor/SET_EDITING_FORMULA', { id: null, type: null })
            openDialog(null, 'inline_formula_type')
          }
        },
        {
          type: 'menuitem',
          text: '图片公式',
          onAction: function() {
            if (!checkBeforeInsert('formula')) return
            store.commit('xmleditor/SET_FIGURE_FORMULA_INSERTING', true)
            setTimeout(() => editor.execCommand('mceImage'))
          }
        }
      ])
    }
  })
  return {
    getMetadata: function () {
      return {
        name: '公式',
        url: 'http://sfrj.cn'
      }
    }
  }
})
